package com.xx.shardingsphere;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xx.db.entity.TOrder;
import com.xx.db.entity.TOrderItem;
import com.xx.db.entity.User;
import com.xx.db.service.ITOrderItemService;
import com.xx.db.service.ITOrderService;
import com.xx.db.service.IUserService;

@RestController
public class HiController {
	@Autowired
	private IUserService service;

	@Autowired
	private ITOrderService orderService;

	@Autowired
	private ITOrderItemService orderItemService;

	/**
	 * 存储，根据分片键
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping("/order/{userId}")
	public String order(@PathVariable int userId) {
		// ID为雪花算法ID
		TOrder entity = new TOrder();

		entity.setOrderNo("NO" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()));
		entity.setUserId(userId);
		orderService.save(entity);
		TOrderItem item = new TOrderItem();
		item.setCreateTime(LocalDateTime.now());
		item.setOrderId(entity.getId());
		item.setOrderNo(entity.getOrderNo());
		item.setUserId(entity.getUserId());
		item.setProduct("name-ffff");
		orderItemService.save(item);
		return "订单NO为：" + entity.getOrderNo();

	}

	/**
	 * 跨片查询
	 * 
	 * @return
	 */
	@RequestMapping("/orders")
	public String orders() {
		List<TOrder> list = orderService.list();
		return list.toString();
	}

	/**
	 * 非跨片查询
	 * 
	 * @return
	 */
	@RequestMapping("/detail/{orderNo}")
	public String detail(@PathVariable String orderNo) {
		TOrder order = orderService.getOne(new QueryWrapper<TOrder>().lambda().eq(TOrder::getOrderNo, orderNo));
		TOrderItem item = orderItemService.getOne(new QueryWrapper<TOrderItem>().lambda()
				.eq(TOrderItem::getOrderId, order.getId()).eq(TOrderItem::getUserId, order.getUserId()));
		return order.toString() + item.toString();

	}

	/**
	 * 非分片表，单表
	 * 
	 * @return
	 */
	@RequestMapping("/user")
	public String home() {
		User entity = new User();
		entity.setGmt(LocalDateTime.now());
		entity.setName("测试用户1");
		service.save(entity);
		return entity.getId() + "";

	}

	/**
	 * 查询非分片表，单表
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping("/getUser/{userId}")
	public String getUser(@PathVariable Integer userId) {
		User entity = service.getById(userId);
		return entity.toString();

	}

}
